package cn.tedu.rtc.mqtt.component;

import cn.tedu.rtc.mqtt.model.TopicConst;
import cn.tedu.rtc.mqtt.service.mqtttopic.IMqttTopicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * 自动订阅
 */
@Component
public class ApplicationBootInitial implements CommandLineRunner {

    @Autowired
    private IMqttTopicService topicService;

    private static final List<String> INIT_TOPICS_SUFFIX = Arrays.asList(
            TopicConst.OSD_SUF,
            TopicConst.STATE_SUF,
            TopicConst.SERVICES_SUF + TopicConst._REPLY_SUF,
            TopicConst.EVENTS_SUF,
            TopicConst.PROPERTY_SUF + TopicConst.SET_SUF + TopicConst._REPLY_SUF);


    /**
     * Subscribe to the devices that exist in the redis when the program starts,
     * to prevent the data from being different from the pilot side due to program interruptions.
     *
     * @param args
     * @throws Exception
     */
    @Override
    public void run(String... args) throws Exception {
        String sn = "8888";
        this.subscribeTopicOnline(sn);
    }

    public void subscribeTopicOnline(String sn) {
        String[] subscribedTopic = topicService.getSubscribedTopic();
        for (String s : subscribedTopic) {
            // If you have already subscribed to the topic of the device, you do not need to subscribe again.
            if (s.contains(sn)) {
                return;
            }
        }
        String prefix = TopicConst.THING_MODEL_PRE + TopicConst.PRODUCT + sn;
        INIT_TOPICS_SUFFIX.forEach(suffix -> topicService.subscribe(prefix + suffix));
    }
}